package com.sharemarking.application.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sharemarking.application.common.entity.Menu;
import com.sharemarking.application.common.repository.MenuRepo;

@Controller
@RequestMapping("menu")
public class MenuController {
	
	@Autowired
	private MenuRepo dao;
	
	@RequestMapping(value="index",method=RequestMethod.GET)
	@PreAuthorize("hasPermission('sys:menu',1)")
	public void index(Menu e,Model model){
		model.addAttribute("search", e);
	}
	
	/**
	 * 获取实体接口
	 * @param e
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.GET)
	@PreAuthorize("hasPermission('sys:menu',1)")
	public String get(Menu obj,Model model){
		if(obj.getId()==0){
			model.addAttribute("obj", obj);
		}else model.addAttribute("obj", dao.findOne(obj.getId()));
		return "menu/form";
	}
	/**
	 * id==0  =>  新增实体
	 * id!=0  =>  更新实体
	 * @param e
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.POST)
	@Transactional
	@PreAuthorize("hasPermission('sys:menu',#target.id==0?8:4)")
	public String post(Menu target,Model model){
		if(target.getId()==0){
			target.setId(null);
			dao.save(target);
			Menu parent=dao.findOne(target.getParentId());
			String path=parent!=null?parent.getPath()+target.getId()+",":target.getId()+",";
			target.setPath(path);
			return "redirect:index";
		}else {
			Menu e=dao.findOne(target.getId());
			if(e==null)return null;
			e.setHref(target.getHref());
			e.setIcon(target.getIcon());
			e.setName(target.getName());
			e.setParentId(target.getParentId());
			e.setPath(target.getPath());
			e.setSort(target.getSort());
			e.setTarget(target.getTarget());
			e.setPermission(target.getPermission());
			e.setSymbol(target.getSymbol());
			dao.save(e);
			Menu parent=dao.findOne(e.getParentId());
			String path=parent!=null?parent.getPath()+target.getId()+",":","+target.getId()+",";
			e.setPath(path);
			return "redirect:index";
		}
	}
	/**
	 * 逻辑删除
	 * @param id
	 */
	@RequestMapping(value="{id}/delete",method=RequestMethod.GET)
	@Transactional
	@PreAuthorize("hasPermission('sys:menu',16)")
	public String delete(@PathVariable("id")Integer id){
		dao.findOne(id).setDelFlag(true);
		return "redirect:../index";
	}
}
